import axios from 'axios';
import React, { useEffect, useRef, useState } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { ListItemRawState } from '../../types';
import { Notify, Swiper, NavBar, ImagePreview, ActionBar } from 'react-vant'
import type { SwiperInstance } from 'react-vant'
import { CartO, ChatO, ShopO } from '@react-vant/icons'
import { useAppDispatch } from '../../app/hooks';
import { addCartList } from '../../features/cart';
import { useCart } from '../../hooks';
const Detail: React.FC = () => {
  // ref
  const swiper = useRef<SwiperInstance>(null)
  // 获取 hooks
  const params = useParams()
  const navigate = useNavigate()
  const dispatch = useAppDispatch()
  const { totalCount } = useCart()
  // 获取动态路由id
  const id = params.id as string;
  // 数据容器
  const [v, setV] = useState<ListItemRawState | null>(null)
  // 请求函数
  const fetchDetailData = async () => {
    const resp = await axios.get(`/api/list/${id}`);
    const { code, message, data } = resp.data;
    if (code === 200) {
      setV(data);
    } else {
      Notify.show({
        type: 'danger',
        message,
        duration: 3000,
        onClose() {
          navigate('/')
        }
      })
    }

  }
  // 图片预览函数
  const openImagePreview = (i: number) => {
    ImagePreview.open({
      images: v?.images,
      teleport: () => document.querySelector('#image-preview') as HTMLElement,
      startPosition: i,
      onChange(index) {
        // 轮播滚动指定位置
        swiper.current?.swipeTo(index)
      }
    })
  }
  // 加入购物车
  const handleAddCar = () => {
    if (!v) return;
    const data = {
      ...v,
      count: 1,
      state: false
    }
    // 加入购物车
    dispatch(addCartList(data))
  }

  // 副作用函数
  useEffect(() => {
    fetchDetailData();
  }, [])

  if (v === null) {
    return <div>数据加载中...</div>
  }


  return (
    <div>
      {/* 头部导航 */}
      <NavBar title={v.title} onClickLeft={() => navigate(-1)}></NavBar>
      {/* 轮播 */}
      <Swiper ref={swiper}>
        {
          v.images.map((v, i) => {
            return <Swiper.Item key={i} onClick={() => openImagePreview(i)}>
              <img src={v} alt="" style={{ width: '100%', height: 200, objectFit: 'cover' }} />
            </Swiper.Item>
          })
        }
      </Swiper>
      {/* 商品信息 */}
      <div className='good-info'>
        <h3>{v.title}</h3>
        <p>{v.desc}</p>
        <h3 style={{ color: 'red', fontWeight: 'bold' }}>¥：{v.price}</h3>
      </div>
      {/* 商品评论 */}
      <h2>商品评论</h2>
      {/* 底部提交栏 */}
      <ActionBar>
        <ActionBar.Icon
          icon={<ChatO />}
          text='客服'
          onClick={() => console.log('chat click')}
        />
        <ActionBar.Icon
          icon={<CartO />}
          text='购物车'
          badge={{ content: totalCount }}
          onClick={() => navigate('/cart')}
        />
        <ActionBar.Icon
          icon={<ShopO />}
          text='店铺'
          onClick={() => console.log('shop click')}
        />
        <ActionBar.Button
          type='danger'
          text='加入购物车'
          onClick={() => handleAddCar()}
        />
      </ActionBar>
    </div>
  )
}


export default Detail